import React, { useEffect, useMemo,useState } from 'react'

/**
 * 单向数据流：父组件产地给子组件的数据，只读不可改
 * @param {*} param0 
 * @returns 
 */
export default function Cart({ cartData,changeCountParent,changeProductStatus }) {
    const [allChecked, setAllChecked] = useState(false)
    //计算属性
    const totalPrice = useMemo(()=>{
        return cartData.filter(item=>item.status).reduce((sum,item)=>{
            return sum += item.count * item.price
        },0)
    },[cartData])
    //更新策略
    useEffect(()=>{
        const result = cartData.every(item=>item.status)
        setAllChecked(result)
    },[cartData])
    return (
        <div>
            <table style={{ width: "100%", borderCollapse: "collapse" }}>
                <thead>
                    <tr>
                        <th>
                            <input checked={allChecked} type="checkbox" />
                        </th>
                        <th>编号</th>
                        <th>图片</th>
                        <th>标题</th>
                        <th>价格</th>
                        <th>数量</th>
                        <th>总价</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {cartData.map(item => {
                        return (
                            <tr>
                                <td>
                                    <input 
                                    checked={item.status} 
                                    type="checkbox" 
                                    onChange={()=>changeProductStatus(item.id)}
                                    />
                                </td>
                                <td>{item.id}</td>
                                <td>
                                    <img width="20px" src={item.imgname} alt="" />
                                </td>
                                <td>{item.title}</td>
                                <td>{item.price}</td>
                                <td>
                                    <button onClick={()=>changeCountParent(item.id,-1)} disabled={item.count == 1}>-</button>
                                    <span>{item.count}</span>
                                    <button onClick={()=>changeCountParent(item.id,1)}>+</button>
                                </td>
                                <td>{item.count * item.price}</td>
                                <td>
                                    <button>删除</button>
                                </td>
                            </tr>
                        )
                    })}

                </tbody>
            </table>
            <p>总价为：{totalPrice}</p>
        </div>
    )
}
